import sys
import bluetooth
from ble_advertising import advertising_payload


import binascii

# 定义事件和标志
_IRQ_CENTRAL_CONNECT = 1
_IRQ_CENTRAL_DISCONNECT = 2
_IRQ_GATTS_WRITE = 3
_IRQ_GATTC_NOTIFY = 4

_FLAG_READ = 0x0002  # 表示特征支持读取操作
_FLAG_WRITE = 0x0008
_FLAG_NOTIFY = 0x0010

# 自定义服务和特征的 UUID
_SERVICE_UUID = bluetooth.UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b")
_CHAR_UUID = bluetooth.UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8")

# 定义服务和特征
_CHAR = (
    _CHAR_UUID,
    _FLAG_READ | _FLAG_WRITE | _FLAG_NOTIFY,
)
_SERVICE = (
    _SERVICE_UUID,
    (_CHAR,),
)
_SERVICES = (_SERVICE,)

class BLEHandler:
    def __init__(self, ble, name="mpy-ble"):
        self._ble = ble
        self._ble.active(True)
        self._ble.irq(self._irq)
        ((self._handle,),) = self._ble.gatts_register_services(_SERVICES)
        self._connections = set()
        self._payload = advertising_payload(name=name, services=[_SERVICE_UUID])
        self._advertise()

    def _irq(self, event, data):
        print("event=")
        print(event)
        if event == _IRQ_CENTRAL_CONNECT:
            print("_IRQ_CENTRAL_CONNECT")
            conn_handle, _, _ = data
            self._connections.add(conn_handle)
        elif event == _IRQ_CENTRAL_DISCONNECT:
            print("_IRQ_CENTRAL_DISCONNECT")
            conn_handle, _, _ = data
            self._connections.remove(conn_handle)
            self._advertise()
        elif event == _IRQ_GATTS_WRITE:
            print("_IRQ_GATTS_WRITE")
            conn_handle, value_handle = data
            if value_handle == self._handle:
                data = self._ble.gatts_read(self._handle)
                print("Received data:", data)
                print("-----------")
                print(binascii.hexlify(data))
                print("-----------")
                byte_array = bytes.fromhex(binascii.hexlify(data))

                string_china = byte_array.decode('utf-8', 'ignore')
                print(string_china)

                # Example usage
                text_string = "H 王博士"
                hex_uint8array = utf8_string_to_hex_uint8array(text_string)
                print(hex_uint8array)

                byte_array = bytes.fromhex(hex_uint8array)

5


                mac_str = binascii.hexlify(data).decode('utf-8', 'ignore')
                print(mac_str)
                
#                 
#                 string_ignore = data.decode()
#                 print(f"忽略错误后的结果: {string_ignore}")

                
                                
#                 try:
#                     # 假设这是一个可能包含无效 UTF-8 编码的字节序列
#                     
#                     utf8_string = data.decode()
#                     print("Received data:", utf8_string)
#                 except Error as e:
#                     print(f"解码时出现错误: {e}")
    

        elif event == _IRQ_GATTC_NOTIFY:
            print("_IRQ_GATTC_NOTIFY")
            conn_handle, value_handle, notify_data = data
            

    def _advertise(self, interval_us=500000):
        self._ble.gap_advertise(interval_us, adv_data=self._payload)

    def send_large_data(self, large_data):
        chunk_size = 20  # BLE 数据包最大长度通常为 20 字节
        for i in range(0, len(large_data), chunk_size):
            chunk = large_data[i:i + chunk_size]
            for conn_handle in self._connections:
                self._ble.gatts_notify(conn_handle, self._handle, chunk)

# 初始化 BLE
ble = bluetooth.BLE()
ble_handler = BLEHandler(ble)

# 测试

def utf8_string_to_hex_uint8array(text):
    """
    Converts a UTF-8 string to a hex-encoded Uint8Array.

    Args:
        text: The UTF-8 string to convert.

    Returns:
        A string representing the hex-encoded Uint8Array.
    """
    utf8_bytes = text.encode('utf-8')
    hex_string = ''.join([f'{byte:02x}' for byte in utf8_bytes])
    return hex_string




# Example usage
text_string = "H 王博士"
hex_uint8array = utf8_string_to_hex_uint8array(text_string)
print(hex_uint8array)

byte_array = bytes.fromhex(hex_uint8array)

string_china = byte_array.decode('utf-8', 'ignore')

print(string_china)
